<template>
    <a-form :model="formData" :labelCol="{span:3}"  @finish="toEditNews" :rules="rules">
        <a-form-item name="title" hasFeedback label="标题">
            <a-input placeholder="新闻标题" v-model:value="formData.title" />
        </a-form-item>
        <a-form-item name="listorder" hasFeedback label="排序">
            <a-input placeholder="排序" style="width:100px" v-model:value="formData.listorder" />
        </a-form-item>
        <a-form-item name="catid" hasFeedback label="分类">
            <a-select v-model:value="formData.catid" style="width:250px">
                <a-select-option v-for="(item,index) in siteState['catList']" :key="index" :value="item['catid']">{{item.catname}}</a-select-option>
            </a-select>
        </a-form-item>
        <a-form-item label="封面">
            <a-upload style="width:250px; display:inline-block;" name="image" @change="uploadimg" :action="siteState['uploadUrl']" :disabled="siteState['uploadStatus']" accept=".jpg,.jpeg,.png,.gif" :headers="headers" :multiple="false" v-model:file-list="fileList">
               <a-button >点击重新上传</a-button>
            </a-upload>
            <img :src="formData.thumb" v-if="formData.thumb" style="width:30px; height:25px; margin-top:5px;" />
        </a-form-item>
        <a-form-item :colLabel="{display:'none'}">
            <div id="content"></div>
        </a-form-item>
        <a-form-item class="text-center">
            <a-button type="primary" :disabled="siteState['btnStatus']" html-type="submit">确认修改</a-button>
        </a-form-item>
    </a-form>
</template>

<style lang="less" scoped>
#content{
    :deep(.w-e-text){
        height: 360px;
    }
}
</style>
<script setup>
import { useRoute } from "vue-router";
import { reactive,ref, toRaw} from "@vue/reactivity";
import { onMounted } from "@vue/runtime-core";
import { message } from "ant-design-vue";
import { useStore } from "vuex";
import E from 'wangeditor-antd';
import { newsCatList,newsEdit } from "@/api/content";

const route=useRoute();

const siteState=reactive({btnStatus:false,uploadStatus:false,catList:[],uploadUrl:import.meta.env.VITE_BASE_URL+"/Files/img"});
message.config({top:'200px'});
const fileList=ref([]);
const store=useStore();
const headers=ref();
const emits=defineEmits(["resetNews"]);
let editor = ref();
let imgsrc=[];
let newsid=route.params['id'];
if(!newsid)
{
    message.error('参数不正确，退出');
    emits("resetNews");
}

const formData=reactive({
    title:'',
    content:'',
    catid:0,
    thumb:'',
});//表单数据

const uploadimg = (info) =>{
    
    if(info.file.status=='uploading')
    {
        siteState.uploadStatus=true;
    }
    else if(info.file.status=='done')
    {
        siteState.uploadStatus=false;
        formData.thumb=info.file.response.data;
        imgsrc.push(info.file.response.data);

    }
    else if (info.file.status === 'error') {
        siteState.uploadStatus=false;
        message.error('无法上传');
    }
    else{
        siteState.uploadStatus=false;
    }
     
};//上传

const checkcatnull= async (_rule,value) =>{
    if(value===0){
        return Promise.reject('请选择分类');
    }

    return Promise.resolve();

};

const checkcat= async (_rule,value) =>{
    if(!value){
        return Promise.reject('请输入标题');
    }
    return Promise.resolve();

};

const rules={
    catid:[{required:true,validator:checkcatnull}],
    title:[{required:true,validator:checkcat}],
}


onMounted(()=>{
    editor.value = new E('#content');
    editor.value.customConfig.menus = [
                'head',  // 标题
                'bold',  // 粗体
                'fontSize',  // 字号
                'fontName',  // 字体
                'italic',  // 斜体
                'foreColor',  // 文字颜色
                'backColor',  // 背景颜色
                'link',  // 插入链接
                'list',  // 列表
                'justify',  // 对齐方式
                'quote',  // 引用
                'emoticon',  // 表情
                'image',  // 插入图片
                'table',  // 表格
                'code',  // 插入代码
                'undo',  // 撤销
                ];
    editor.value.customConfig.uploadImgServer=import.meta.env.VITE_BASE_URL+"/Files/img";            
    editor.value.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
    editor.value.customConfig.uploadFileName = 'image';
    editor.value.customConfig.uploadImgTimeout = 15000;
    editor.value.customConfig.uploadImgHeaders = {'access-token':store.getters['auth/tokken']};
    editor.value.customConfig.onchange=function (newHtml) {                
                formData.content=newHtml;
    };

    editor.value.customConfig.uploadImgHooks = {
                customInsert: function (insertImg, result, editor) {
                    
                    if(result['code']==200)
                    {
                        let url=result['data'];
                        insertImg(url);
                        imgsrc.push(url);
                    }
                    else if(result['code']==0)
                    {
                        message.error(result['msg']);
                    }
                },
                timeout: function (xhr, editor) {
                    //console.log(xhr);                    
                    message.error('上传超时');
                },
                error: function (xhr, editor) {
                   // console.log(xhr);
                    
                }
    };

    editor.value.create();
    

});//--编辑框完成

newsCatList().then(
    res=>{
        //console.log(res.data);
        if(res.data['code']==200)
        {
            siteState.catList=res.data['data'];

            newsEdit({id:newsid}).then(
                res=>{
                    if(res.data['code']==200)
                    {
                        formData.title=res.data['data']['title'];
                        formData.catid=res.data['data']['catid'];
                        formData.listorder=res.data['data']['listorder'];
                        formData.content=res.data['data']['content'];
                        formData.thumb=res.data['data']['thumb'];
                        editor.value.txt.html(formData.content);
                    }
                    else{
                        message.error(res.data['msg']);
                        emits("resetNews");
                    }
                },  
                err=>{
                    console.log(err);
                }
            )
        }
        else{
            message.error('返回错误');
        }
        
    },
    err=>{
        console.log(err)
    }
);//加载分类


const toEditNews= () =>{
    const obj={...toRaw(formData),imgs:imgsrc,id:newsid};
    newsEdit(obj).then(
        res=>{
            if(res.data['code']==200)
            {
                message.success('修改成功');
                emits("resetNews");
            }
            else{
                message.error(res.data['msg']);

            }
        },
        err=>{
            console.log(err)
        }
    )
};//添加新闻


</script>
